// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.model.validators;

import java.util.regex.Pattern;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.User;
import static net.taviscaron.drivenotes.server.util.ExceptionUtils.invalidEntityException;

/**
 * Validate new user
 * @author Andrei Senchuk
 */
public class NewUserValidator implements Validator<User> {
    private static final String EMAIL_PATTERN = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

    public enum Error {
        INVALID_USERNAME, INVALID_EMAIL, INVALID_PASSWORD
    }

    public void validate(User user) throws InvalidEntityException {
        if(user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw invalidEntityException(Error.INVALID_USERNAME);
        }

        if(user.getEmail() == null || !Pattern.matches(EMAIL_PATTERN, user.getEmail())) {
            throw invalidEntityException(Error.INVALID_EMAIL);
        }

        if(user.getPassword() == null || user.getUsername().trim().isEmpty()) {
            throw invalidEntityException(Error.INVALID_PASSWORD);
        }
    }
}
